﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BitworkStudios.ClockNet.Core.Contracts;
using BitworkStudios.ClockNet.Core.Sntp;

namespace BitworkStudios.ClockNet.Core
{
    public class TimeKeeperService : ITimeKeeperService
    {
        public IConfiguration Configuration { get; set; }

        public TimeKeeperService(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public Models.DateTime GetCurrentDecimalTime()
        {
            var currentTime = new DateTime();

            foreach (var timeServer in Configuration.TimeServers)
            {
                currentTime = SntpClient.GetNow(new RemoteSntpServer((string) timeServer, Configuration.Port), Configuration.Timeout).ToUniversalTime();
                if (currentTime != DateTime.MinValue)
                {
                    break;
                }
            }

            return GetDecimalTime(currentTime);
        }

        public Models.DateTime GetDecimalTime(DateTime time)
        {
            //var test = new DateTime(time.Year, time.Month, time.Day, 23, 59, 59, 99); 
            //10 Hours per day
            //100 Minutes per hour
            //100 Seconds per minute
            var epoch = new DateTime(time.Year, time.Month, time.Day, 0, 0, 0, 0);
            TimeSpan totalSpan = time - epoch;

            double totalSecondsElapsed = totalSpan.TotalSeconds;
            double totalDecimalSecondsElapsed = totalSecondsElapsed/0.864d;

            double decimalHours = totalDecimalSecondsElapsed/(100d*100d);
            double decimalMinutes = (decimalHours - Math.Floor(decimalHours)) * 100d;
            double decimalSeconds = (decimalMinutes - Math.Floor(decimalMinutes)) * 100d;

            var decimalTime = new Models.DateTime
            {
                Day = time.Day,
                Month = time.Month,
                Cycle = time.Year,
                Hour = (int)Math.Floor(decimalHours),
                Minute = (int)Math.Floor(decimalMinutes),
                Second = (int)Math.Floor(decimalSeconds)
            };

            return decimalTime;
        }
    }
}
